package edu.nf.vac.announcement.service;

import cn.hutool.core.bean.BeanUtil;
import edu.nf.vac.announcement.dao.AnnouncementDTO;
import edu.nf.vac.announcement.dao.AnnouncementDao;
import edu.nf.vac.announcement.dao.AnnouncementPageDTO;
import edu.nf.vac.announcement.entity.Announcement;
import edu.nf.vac.announcement.exception.AnnouncementException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageInfo;

import java.util.Date;
import java.util.List;

/**
 * @author LQJ
 * @date 2022/3/29
 */
@Slf4j
@DubboService(interfaceClass = AnnouncementService.class,version = "1.0.0")
@Transactional(rollbackFor = RuntimeException.class)
public class AnnouncementServiceImpl implements AnnouncementService{
    @Autowired
    private AnnouncementDao dao ;
    @Override
    public AnnouncementPageDTO listAnnouncement(int pageNum, int pageSize) {
        List<Announcement> list = dao.listAnnouncement(pageNum, pageSize);
        PageInfo<Announcement> pageInfo = new PageInfo<>(list);
        AnnouncementPageDTO pageDTO = BeanUtil.copyProperties(pageInfo, AnnouncementPageDTO.class);
        return pageDTO;
    }

    @Override
    public void addAnnouncement(AnnouncementDTO announcementDTO) {
        try {
            Announcement announcement = BeanUtil.copyProperties(announcementDTO, Announcement.class);
            announcement.setCreateTime(new Date(System.currentTimeMillis()));
            dao.saveAnnouncement(announcement);
        }catch (RuntimeException e){
            log.error(e.getMessage());
            throw new AnnouncementException("发送公告失败",e);
        }

    }

    @Override
    public AnnouncementDTO getAnnouncementById(int id) {
        Announcement announcement = dao.getAnnouncementById(id);
        AnnouncementDTO dto = BeanUtil.copyProperties(announcement, AnnouncementDTO.class);
        return dto;


    }

    @Override
    public void updateAnnouncement(AnnouncementDTO announcement) {
        try {
            Announcement dto = BeanUtil.copyProperties(announcement, Announcement.class);
            dao.updateAnnouncement(dto);

        }catch (RuntimeException e){
            log.error(e.getMessage());
            throw new AnnouncementException("更新公告失败",e);
        }

    }
}
